﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BCCommon;
using BCData.WeChatComponent.WeChatUserInfo;
using BCData.WeChatComponent.WeChatUserTag;
using BCDto.WeChatComponent.WeChatUserTag;
using BCEntity.WeChatComponent.WeChatUserInfo;
using BCEntity.WeChatComponent.WeChatUserTag;
using BCService.Utils;
using Newtonsoft.Json;
using WeChatSDK.WeChatDto.User;
using WeChatSDK.WeChatServiceComponent.User;

namespace BCService.WeChatComponent.WeChatUserTagService
{
    /// <summary>
    /// 微信用户标签服务
    /// </summary>
    public class WeChatUserTagService : IWeChatUserTagService
    {
        private readonly IWeChatUserTagData weChatUserTagData;
        private readonly IWeChatUserInfoData weChatUserInfoData;
        private readonly WeChatUserService weChatUserService;

        public WeChatUserTagService(IWeChatUserTagData weChatUserTagData,
            IWeChatUserInfoData weChatUserInfoData)
        {
            this.weChatUserTagData = weChatUserTagData;
            this.weChatUserInfoData = weChatUserInfoData;
            this.weChatUserService = new WeChatUserService();
        }

        public WeChatUserTagDto Add(string name)
        {
            CheckUserTagData(name);
            IEnumerable<WeChatUserTagEntity> weChatUserTagEntities = this.weChatUserTagData.Get();
            if (weChatUserTagEntities.Any(p => p.Name.Equals(name)))
            {
                throw new ArgumentException("用户标签已存在。");
            }
            if (weChatUserTagEntities.Count() == 100)
            {
                throw new ArgumentException("用户标签最多100个。");
            }
            string response = WeChatHttpResponseHandle.ProcessMessage(this.weChatUserService.AddUserTag(new UserTagDto() { Tag = new UserTagDetailsDto() { Name = name } }));
            dynamic result = JsonConvert.DeserializeObject<dynamic>(response);
            WeChatUserTagEntity weChatUserTagEntity = new WeChatUserTagEntity()
            {
                WeChatUserTagId = result.tag.id,
                Name = result.tag.name
            };
            this.weChatUserTagData.Add(weChatUserTagEntity);
            return weChatUserTagEntity.As<WeChatUserTagDto>();
        }

        public void Delete(int id)
        {
            if (id < 3)
            {
                throw new ArgumentException("无法删除微信默认标签！");
            }
            WeChatHttpResponseHandle.ProcessMessage(this.weChatUserService.DeleteUserTag(new UserTagDto() { Tag = new UserTagDetailsDto() { Id =id } }));
            this.weChatUserTagData.Delete(id);
        }

        public PageableList<WeChatUserTagDto> Get(string name, DateTime? start, DateTime? end, bool? ascending, int pageIndex = 1, int pageSize = 10)
        {
            if (start.HasValue && end.HasValue)
            {
                if (start > end)
                {
                    throw new ArgumentException("开始时间不能大于结束时间！");
                }
            }
            IEnumerable<WeChatUserTagEntity> weChatUserTagEntities = this.weChatUserTagData.Get();
            if (!string.IsNullOrWhiteSpace(name))
            {
                weChatUserTagEntities = weChatUserTagEntities.Where(p => p.Name.Contains(name));
            }
            if (start.HasValue)
            {
                weChatUserTagEntities = weChatUserTagEntities.Where(p => p.CreateTime>=start.Value);
            }
            if (end.HasValue)
            {
                weChatUserTagEntities = weChatUserTagEntities.Where(p => p.CreateTime <= end.Value);
            }
            if (ascending.HasValue && !ascending.Value)
            {
                weChatUserTagEntities = weChatUserTagEntities.OrderByDescending(p=>p.WeChatUserTagId);
            }
            else
            {
                weChatUserTagEntities = weChatUserTagEntities.OrderBy(p => p.WeChatUserTagId);
            }
            int count = weChatUserTagEntities.Count();
            weChatUserTagEntities = weChatUserTagEntities.Skip((pageIndex-1) * pageSize);
            return new PageableList<WeChatUserTagDto>()
            {
                Count = count,
                Items = weChatUserTagEntities.As<IEnumerable<WeChatUserTagDto>>()
            };
        }
        public IEnumerable<WeChatUserTagDto> Get()
        {
            return this.weChatUserTagData.Get().As<IEnumerable<WeChatUserTagDto>>();
        }

        public void Mark(long tagid, string openid)
        {
            WeChatUserInfoEntity user =  this.weChatUserInfoData.GetEntity(openid);
            if (user == null)
            {
                throw new ArgumentException("此微信用户不存在！");
            }
            List<string> userTags = user.TagidList.Split(",").ToList();
            if (userTags.Count >= 20)
            {
                throw new ArgumentException("此用户标签已达上限，无法继续添加！");
            }
            List<string> openids = new List<string>();
            openids.Add(openid);
            WeChatHttpResponseHandle.ProcessMessage(this.weChatUserService.BatchTagging(tagid, openids));
            userTags.Add(tagid.ToString());
            user.TagidList = string.Join(",", userTags);
            this.weChatUserInfoData.Update(user);
        }
        public void UnMark(long tagid, string openid)
        {
            WeChatUserInfoEntity user = this.weChatUserInfoData.GetEntity(openid);
            if (user == null)
            {
                throw new ArgumentException("此微信用户不存在！");
            }
            List<string> userTags = user.TagidList.Split(",").ToList();
            if (!userTags.Contains(tagid.ToString()))
            {
                throw new ArgumentException("此用户不存在此标签，无法继续移除！");
            }
            List<string> openids = new List<string>();
            openids.Add(openid);
            WeChatHttpResponseHandle.ProcessMessage(this.weChatUserService.BatchUnTagging(tagid, openids));
            userTags.Remove(tagid.ToString());
            user.TagidList = string.Join(",", userTags);
            this.weChatUserInfoData.Update(user);
        }
        public void SynchronizeUserTags()
        {
            string response = WeChatHttpResponseHandle.ProcessMessage(this.weChatUserService.GetUserTag());
            dynamic result = JsonConvert.DeserializeObject<dynamic>(response);
            int count = (int)result.tags.Count;
            this.weChatUserTagData.Delete();
            for (int i = 0; i < count; i++)
            {
                WeChatUserTagEntity weChatUserTagEntity = new WeChatUserTagEntity()
                {
                    WeChatUserTagId = result.tags[i].id,
                    Name = result.tags[i].name
                };
                this.weChatUserTagData.Add(weChatUserTagEntity);
            }
        }

        public WeChatUserTagDto Update(int id, string name)
        {
            if (id < 3)
            {
                throw new ArgumentException("微信默认标签，无法修改！");
            }
            CheckUserTagData(name);
            IEnumerable<WeChatUserTagEntity> weChatUserTagEntities = this.weChatUserTagData.Get();
            if (weChatUserTagEntities.Any(p => p.Name.Equals(name)&&p.WeChatUserTagId!=id))
            {
                throw new ArgumentException("用户标签已存在。");
            }
            if (weChatUserTagEntities.Count() == 100)
            {
                throw new ArgumentException("用户标签最多100个。");
            }
            string response = WeChatHttpResponseHandle.ProcessMessage(this.weChatUserService.UpdateUserTag(new UserTagDto() { Tag = new UserTagDetailsDto() { Id=id,Name = name } }));
            dynamic result = JsonConvert.DeserializeObject<dynamic>(response);
            WeChatUserTagEntity weChatUserTagEntity = new WeChatUserTagEntity()
            {
                WeChatUserTagId = id,
                Name = name
            };
            this.weChatUserTagData.Update(weChatUserTagEntity);
            return weChatUserTagEntity.As<WeChatUserTagDto>();
        }

        private void CheckUserTagData(string name)
        {
            if (name.Length > 30)
            {
                throw new ArgumentException("用户标签名称最长不可以超过30个字符。");
            }
        }
    }
}
